<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps<{
    isDisabled?: boolean
}>()

const { isDisabled } = toRefs(props)
// const typeOptions = ['年榜', '季榜', '月榜', '周榜']
const typeOptions = [
    { value: '4', label: '年榜' },
    { value: '3', label: '季榜' },
    { value: '2', label: '月榜' },
    { value: '1', label: '周榜' },
]
const selectedType = defineModel<string>('timeType', { required: true })
const selectedRange = defineModel<string>('timeStr', { required: true })
const rangeOptions = ref<{ label: string, value: string }[]>([])

// 获取当前时间
const now = new Date()

// 获取上周日作为周结束日
function getLastWeekEnd() {
    const date = new Date()
    date.setDate(date.getDate() - date.getDay()) // 上周日
    return date
}

// 获取上个月最后一天
function getLastMonthEnd() {
    const date = new Date()
    date.setMonth(date.getMonth(), 0) // 上个月最后一天
    return date
}

// 获取上个季度结束日
function getLastQuarterEnd() {
    const date = new Date()
    const quarter = Math.floor(date.getMonth() / 3)
    const lastQuarter = quarter === 0 ? 3 : quarter - 1
    date.setMonth(lastQuarter * 3 + 2, 0) // 上个季度最后一天
    return date
}

// 格式化日期为 YYYY.MM.DD
function formatDate(date: Date): string {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}.${month}.${day}`
}

// 生成周区间
function generateWeekOptions() {
    const options: { label: string, value: string }[] = []
    // 从2023年1月2日（第一周）开始
    const startDate = new Date(2023, 0, 2)
    const endDate = getLastWeekEnd() // 动态截止到上周日

    // 从最近一周开始倒序生成
    let currentEnd = new Date(endDate)
    while (currentEnd >= startDate) {
        const weekStart = new Date(currentEnd)
        weekStart.setDate(weekStart.getDate() - 6) // 一周开始日期

        // 如果开始日期早于2023.01.02，则调整为2023.01.02
        const adjustedStart = weekStart < startDate ? new Date(startDate) : weekStart

        const startStr = formatDate(adjustedStart)
        const endStr = formatDate(currentEnd)
        options.unshift({ // 使用unshift保证倒序插入
            label: `${startStr} - ${endStr}`,
            value: `${startStr.replace(/\./g, '')}-${endStr.replace(/\./g, '')}`,
        })

        // 上一周（减7天）
        currentEnd = new Date(currentEnd)
        currentEnd.setDate(currentEnd.getDate() - 7)
    }

    return options
}

// 生成月区间
function generateMonthOptions() {
    const options: { label: string, value: string }[] = []
    const endDate = getLastMonthEnd() // 上个月最后一天

    // 从2023年1月开始
    const startYear = 2023
    const startMonth = 0 // 0表示1月

    // 从最近一个月开始倒序生成
    let currentYear = endDate.getFullYear()
    let currentMonth = endDate.getMonth()

    while (currentYear > startYear || (currentYear === startYear && currentMonth >= startMonth)) {
        const startDate = new Date(currentYear, currentMonth, 1)
        const endDate = new Date(currentYear, currentMonth + 1, 0)

        const startStr = formatDate(startDate)
        const endStr = formatDate(endDate)
        options.unshift({
            label: `${currentYear}年${currentMonth + 1}月 (${startStr} - ${endStr})`,
            value: `${startStr.substring(0, 7).replace('.', '')}`,
        })

        // 上个月
        if (currentMonth === 0) {
            currentYear--
            currentMonth = 11
        }
        else {
            currentMonth--
        }
    }

    return options
}

// 生成季区间
function generateSeasonOptions() {
    const options: { label: string, value: string }[] = []
    const quarters = [
        { name: 'Q1', months: [0, 1, 2] }, // 1-3月
        { name: 'Q2', months: [3, 4, 5] }, // 4-6月
        { name: 'Q3', months: [6, 7, 8] }, // 7-9月
        { name: 'Q4', months: [9, 10, 11] }, // 10-12月
    ]

    const endDate = getLastQuarterEnd()
    let currentQuarter = Math.floor(endDate.getMonth() / 3)
    let currentYear = endDate.getFullYear()

    // 从2023年Q1开始
    const startYear = 2023
    const startQuarter = 0

    // 从最近季度开始倒序生成
    while (currentYear > startYear || (currentYear === startYear && currentQuarter >= startQuarter)) {
        const quarter = quarters[currentQuarter]
        const startMonth = quarter.months[0]
        const endMonth = quarter.months[2]

        const startDate = new Date(currentYear, startMonth, 1)
        const endDate = new Date(currentYear, endMonth + 1, 0)

        const startStr = formatDate(startDate)
        const endStr = formatDate(endDate)
        options.unshift({
            label: `${currentYear}年第${currentQuarter + 1}季度 (${startStr} - ${endStr})`,
            value: `${currentYear}Q${currentQuarter + 1}`,
        })

        // 上个季度
        if (currentQuarter === 0) {
            currentYear--
            currentQuarter = 3
        }
        else {
            currentQuarter--
        }
    }

    return options
}

// 生成年区间
function generateYearOptions() {
    const options: { label: string, value: string }[] = []
    const currentYear = now.getFullYear()
    const lastYear = currentYear

    for (let year = 2023; year <= lastYear; year++) {
        options.push({
            label: `${year}`,
            value: `${year}`,
        })
    }

    return options
}

// 榜单类型变化处理
watch(selectedType, () => {
    handleTypeChange()
})
function handleTypeChange() {
    switch (selectedType.value) {
        case '1':
            rangeOptions.value = generateWeekOptions().reverse()
            break
        case '2':
            rangeOptions.value = generateMonthOptions().reverse()
            break
        case '3':
            rangeOptions.value = generateSeasonOptions().reverse()
            break
        case '4':
            rangeOptions.value = generateYearOptions().reverse()
            break
        case '':
            rangeOptions.value = []
            break
        case undefined:
            selectedType.value = ''
            rangeOptions.value = []
            break
    }
    // 默认选中第一项
    if (rangeOptions.value.length > 0) {
        selectedRange.value = rangeOptions.value[0].value
    }
}

// 初始化
handleTypeChange()
</script>

<template>
    <div class="container">
        <el-select v-model="selectedType"
                   placeholder="请选择榜单类型"
                   style="width: 150px;"
                   :disabled="isDisabled"
                   @change="handleTypeChange"
        >
            <el-option v-for="item in typeOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"
            />
        </el-select>

        <el-select v-model="selectedRange"
                   placeholder="请选择时间区间"
                   :disabled="isDisabled"
        >
            <el-option v-for="(item, index) in rangeOptions"
                       :key="index"
                       :label="item.label"
                       :value="item.value"
            />
        </el-select>
    </div>
</template>

<style scoped>
.container {
    display: flex;
    gap: 10px;
}
</style>
